package com.example.guestbook.view;

import java.net.URL;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import com.example.guestbook.po.Greeting;
import com.example.guestbook.service.GuestBookService;
import com.gaeig.base.BaseView;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.inject.Inject;

public class GuestBookView extends BaseView {

  @Inject
  private GuestBookService guestBookService;

  private String content;

  public GuestBookService getGuestBookService() {
    return guestBookService;
  }

  public void setGuestBookService(GuestBookService guestBookService) {
    this.guestBookService = guestBookService;
  }

  public List<Greeting> getAllGreetings() throws Exception {
    return guestBookService.getAllGreetings();
  }

  public String getTitle() {
    return "Guest Book";
  }

  public String newGreeting() {
    Greeting greeting = new Greeting();
    greeting.setContent(content);
    greeting.updateChangeLog();
    guestBookService.saveGreeting(greeting);
    return "success";
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

  public String getRequestGoogleService() {
    String requestUrl = AuthSubUtil.getRequestUrl("http://localhost:8080/gdata/googleService.jsf", "http://www.google.com/calendar/feeds/", false,
        true);
    return requestUrl;
  }

  public String getGooleDoc() throws Exception {
    String singleUseToken = AuthSubUtil.getTokenFromReply(((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
        .getQueryString());
    String sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null);

    CalendarService calendarService = new CalendarService("localhost-docService-1");
    calendarService.setAuthSubToken(sessionToken, null);

    URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
    CalendarFeed resultFeed = calendarService.getFeed(feedUrl, CalendarFeed.class);

    StringBuilder builder = new StringBuilder();
    builder.append("Your calendars:\n");
    for (int i = 0; i < resultFeed.getEntries().size(); i++) {
      CalendarEntry entry = resultFeed.getEntries().get(i);
      builder.append("\t" + entry.getTitle().getPlainText());
    }
    return builder.toString();
  }

}
